const { skuDetail, posterList, picPoster, getUser } = require("../../../utils/api")
import Poster from './component/palette/poster' //数据来源
// pages/picdetail/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bookList: [], //isHave 0 没有该图鉴  1有该图鉴
    skuId: '',
    haveNum: '',
    countNum: '',
    skuDetail: {},
    page: 1,
    limit: 4,
    showBackBtn: false,
    posterList: [],
    yulanList: [],
    imagePath: '',
    downPoster: false,
    headimg: '',
    nickname: '',
    userid: '',
    posterBg: '',
    showPhone: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      skuId: options.skuid,
    })
    this.getSkuDetail()
    this.getPoster()
    this.getUserInfo()

    const userInfo = JSON.parse(wx.getStorageSync('userInfo'));
    this.setData({
      headimg: userInfo.avatar,
      nickname: userInfo.nickname,
      userid: userInfo.id
    })

  },
  async getUserInfo() {
    await getUser().then((res) => {
      if (res.errcode == 0) {
        if (!res.user.phone) {
          this.setData({
            showPhone: true
          })
        } else {
          return
        }
      }
      else {
        wx.showToast({
          title: res.errmsg,
          icon: 'none',
        });
      }

    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  //获取图鉴详情
  async getSkuDetail() {
    let params = {
      series_num: this.data.skuId,
      page: this.data.page,
      limit: this.data.limit
    }
    await skuDetail(params).then((res) => {
      if (res.errcode == 0) {
        let resData = res.data.colldata.skus
        this.setData({
          bookList: resData.skus,
          haveNum: resData.havecount,
          countNum: resData.count,
          skuDetail: res.data.colldata.series
        })
      } else {
        wx.showToast({
          title: res.errmsg,
          icon: 'none',
        });
      }
    })
  },

  async getPoster() {
    let params = {
      series_num: this.data.skuId,
    }
    await posterList(params).then((res) => {

      if (res.errcode == 0) {
        this.setData({
          posterList: res.data.skuimgdata.imgurls,
          yulanList: res.data.skuimgdata.haveimgurls,
          posterBg: res.data.skuimgdata.back_url
        })

      }
    })
  },

  swiperChange(e) {
    this.setData({
      showBackBtn: true,
      page: e.detail.current + 1
    })
    this.getSkuDetail()
    if (this.data.page == 1) {
      this.setData({
        showBackBtn: false
      })
    }
  },
  //下一页
  nextPage() {
    if (this.data.countNum <= this.data.page * this.data.limit) {
      wx.showToast({
        title: '没有更多了',
        icon: 'none',
      });
    } else {
      this.setData({
        showBackBtn: true,
        page: ++this.data.page
      })
      this.getSkuDetail()
    }

  },

  //上一页
  backPage() {
    if (this.data.page * this.data.limit <= 4) {
      return
    } else {
      this.setData({
        showBackBtn: true,
        page: --this.data.page
      })
      this.getSkuDetail()
    }

    if (this.data.page == 1) {
      this.setData({
        showBackBtn: false
      })
    }
  },

  onBack() {
    wx.navigateBack({
      delta: 1
    })
  },

  //下载海报
  toDownload(e) {

    let type = e.currentTarget.dataset.type
    this.setData({
      downPoster: true
    })
    let posterParams = {
      avatar: this.data.headimg, //头像
      userName: this.data.nickname, //昵称
      userId: this.data.userid, //用户id
      haveNum: this.data.haveNum, //收集数量
      countNum: this.data.countNum,//总数
      posterBg: this.data.posterBg,//背景
      posterList: type == 'user' ? this.data.posterList : this.data.yulanList
    }

    wx.showToast({
      title: '海报绘制中',
      icon: 'loading',
      duration: 4000,
      mask: false,
      success: (result) => {
        this.setData({
          paintPallette: new Poster().palette(posterParams),
        });
      },

    });


  },


  onImgOK(e) {
    this.imagePath = e.detail.path;
    var fileManager = wx.getFileSystemManager().readFileSync(e.detail.path, "base64");
    this.setData({
      image: this.imagePath,
    });

    //领取奖励接口
    let params = {
      series_num: this.data.skuId,
    }
    picPoster(params).then((res) => {
    })

    wx.previewImage({
      current: this.imagePath, // 当前显示图片的http链接
      urls: [this.imagePath] // 需要预览的图片http链接列表
    })


    // this.saveImage(this.imagePath);

  },


  saveImage(e) {
    wx.showToast({
      title: '海报绘制中',
      icon: 'loading',
      duration: 2000,
    });

    wx.saveImageToPhotosAlbum({
      filePath: e,
      success: function (data) {
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: '您的分享海报已保存到相册',
          showCancel: false,
        })
      },
      fail: function (err) {
        if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
          // 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
          wx.showModal({
            title: '提示',
            content: '需要您授权保存相册',
            showCancel: false,
            success: modalSuccess => {
              wx.openSetting({
                success(settingdata) {

                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    wx.showModal({
                      title: '提示',
                      content: '获取权限成功,再次点击图片即可保存',
                      showCancel: false,
                    })
                  } else {
                    wx.showModal({
                      title: '提示',
                      content: '获取权限失败，将无法保存到相册哦~',
                      showCancel: false,
                    })
                  }
                },
                fail(failData) {

                },
                complete(finishData) {

                }
              })
            }
          })
        }
      },
      complete(res) {
        wx.hideLoading()
      }
    })

  },

  onImgErr(e) {

    wx.showToast({
      title: '下载失败，刷新页面重新尝试',
      icon: 'none',
    });

  }


})